package com.aco.fatureapp.utilitary;

import java.util.List;

import org.apache.http.NameValuePair;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalBase64;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import com.aco.fatureapp.model.ConfiguracaoApp;

public class SoapHttpRequest {

	private final String NAMESPACE = "http://service.soap.fatureweb.ac.com.br/";

	private SoapObject mRequestSoap;

	static ConfiguracaoApp sConfiguracaoApp = null;

	public static String getSoapServiceURL() {

		if (sConfiguracaoApp == null) {
			sConfiguracaoApp = ConfiguracaoApp.findAll(ConfiguracaoApp.class)
					.next();
		}

		return "http://" + sConfiguracaoApp.getIpConexao() + ":"
				+ sConfiguracaoApp.getPortaDeConecao()
				+ "/ifature/fileServiceBean";
	}

	public void execute(final byte[] file, final String fileName,
			final List<NameValuePair> params) throws Exception {

		this.mRequestSoap = new SoapObject(NAMESPACE, "receiveFile");

		final PropertyInfo pi = new PropertyInfo();
		pi.setName("file");
		pi.setValue(file);
		pi.setType(MarshalBase64.BYTE_ARRAY_CLASS);

		mRequestSoap.addProperty(pi);
		mRequestSoap.addProperty("fileName", fileName);

		/*
		 * Criar os parâmetros a serem enviados ao servidor.
		 */
		for (final NameValuePair param : params) {
			mRequestSoap.addProperty(param.getName(),
					String.valueOf(param.getValue()));
		}

		final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);

		envelope.setOutputSoapObject(mRequestSoap);

		final MarshalBase64 md = new MarshalBase64();
		md.register(envelope);

		final HttpTransportSE androidHttpTransport = new HttpTransportSE(
				getSoapServiceURL(), 999999999);

		androidHttpTransport.debug = true;

		androidHttpTransport.call(NAMESPACE + "receiveFile", envelope);
	}
}
